import UpdateClass, { UpdateClassMethods } from '@/pages/Admin/ManageClass/components/UpdateClass';
import {
  addStudentsByClassUsingPost,
  deleteClassByIdUsingDelete,
  getStudentListDontSelectClassUsingGet,
  pageClassesUsingPost,
} from '@/services/student-management-system/banjimokuai';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Modal, Select, Space, Table } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

const ManageClass: React.FC = () => {
  const initSearchParam = {
    current: 1,
    pageSize: 6,
  };

  const [queryParam, setQueryParam] = useState<API.ClassDTO>({ ...initSearchParam });
  const [open, setOpen] = useState<boolean>(false);
  const [total, setTotal] = useState<number>(0);
  const [editClass, setEditClass] = useState<API.ClassDTO>({});
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');
  const childRef = useRef<UpdateClassMethods>(null);
  const [isAddStudentModalOpen, setIsAddStudentModalOpen] = useState(false);
  const [addStudentClassId, setAddStudentClassId] = useState<number>(0);
  const [isAbleAddClassStudents, setIsAbleAddClassStudents] = useState<API.UserVO[]>([]);
  const [addStudentModelForm] = Form.useForm();

  const handleOnEdit = (record: API.ClassVO) => {
    setTitle('编辑');
    setEditClass({ ...record });
    setOpen(true);
  };

  const handleAddStudent = (record: API.ClassVO) => {
    addStudentModelForm.setFieldsValue(record);
    setAddStudentClassId(record.id ?? 0);
    setIsAddStudentModalOpen(true);
  };

  const handleOnDelete = async (record: API.ClassVO) => {
    const res = await deleteClassByIdUsingDelete({ id: record.id ?? -1 });
    if (res.code === 200) {
      message.success('删除成功');
      // 这里进行处理
      // 刷新页面
      window.location.reload();
    } else {
      message.error('删除失败：' + res.msg);
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '班级名称', dataIndex: 'className', key: 'className' },
    { title: '年级', dataIndex: 'grade', key: 'grade' },
    { title: '专业', dataIndex: 'major', key: 'major' },
    { title: '人数', dataIndex: 'stuCount', key: 'stuCount' },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '更多',
      dataIndex: 'options',
      render: (_: any, record: any) => (
        <Space>
          <Button size="small" onClick={() => handleAddStudent(record)}>
            添加学生
          </Button>
          <Button size="small" onClick={() => handleOnEdit(record)}>
            编辑
          </Button>
          <Button size="small" danger onClick={() => handleOnDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const [dataSource, setDataSource] = useState<API.ClassVO[]>([]);

  const getClasses = async () => {
    console.log(queryParam);
    const res = await pageClassesUsingPost({ ...queryParam });
    if (res.code === 200) {
      message.success('获取数据成功');
      setDataSource(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } else {
      message.error('获取数据失败：' + res.msg);
    }
  };

  const handleSearch = (values: any) => {
    setQueryParam({ ...queryParam, ...values });
  };

  const handleOk = async () => {
    setConfirmLoading(true);
    try {
      const success = await childRef.current?.submitForm();
      if (success) {
        setOpen(false);
        getClasses();
      }
    } catch (error) {
      message.error('提交数据有误，请检查后再提交');
    } finally {
      setConfirmLoading(false); // 无论成功还是失败都应重置loading状态
    }
  };

  const handleCancel = () => setOpen(false);

  const handleAddClass = () => {
    setOpen(true);
    setTitle('新增');
    setEditClass({});
  };

  // 添加学生modal
  const handleAddStudentOk = () => {
    // 触发表单提交
    addStudentModelForm.submit();
  };

  // 取消添加学生modal
  const handleAddStudentCancel = () => {
    addStudentModelForm.resetFields();
    setIsAddStudentModalOpen(false);
  };

  const onAddStudentFinish = async (values: any) => {
    const studentIds = values.students;
    const res = await addStudentsByClassUsingPost({
      studentIds: studentIds,
      classId: addStudentClassId,
    });
    if (res.code === 200) {
      message.success('添加成功');
      setIsAddStudentModalOpen(false);
      addStudentModelForm.resetFields();
      // 重新获取数据
      getStudentsDontSelectClass();
      getClasses();
    } else {
      message.error('添加失败：' + res.msg);
    }
    handleCancel(); // 关闭弹窗
  };

  // 获取未选班级列表
  const getStudentsDontSelectClass = async () => {
    const res = await getStudentListDontSelectClassUsingGet();
    if (res.code === 200) {
      // 这里根据api 获取学生列表
      setIsAbleAddClassStudents(res.data ?? []);
    } else {
      message.error('获取学生数据失败');
    }
  };

  useEffect(() => {
    getClasses();
    getStudentsDontSelectClass();
  }, [queryParam]);

  return (
    <>
      <div className="ManageClass">
        <Form
          name="searchForm"
          layout="inline"
          onFinish={handleSearch}
          initialValues={{ ...queryParam }}
        >
          <Form.Item name="className" label="班级名称">
            <Input style={{ width: 120 }} placeholder="请输入班级名称" />
          </Form.Item>
          <Form.Item name="grade" label="年级">
            <Input style={{ width: 120 }} placeholder="请输入年级" />
          </Form.Item>
          <Form.Item name="major" label="专业">
            <Input style={{ width: 120 }} placeholder="请输入专业" />
          </Form.Item>
          <Form.Item>
            <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>

        <Space style={{ marginTop: 10, marginBottom: 5 }}>
          <Button type="primary" onClick={handleAddClass}>
            新增班级
          </Button>
        </Space>

        <Table
          columns={columns}
          dataSource={dataSource}
          pagination={{
            total,
            current: queryParam.current,
            pageSize: queryParam.pageSize,
            onChange: (current, pageSize) =>
              setQueryParam({ ...initSearchParam, current, pageSize }),
          }}
        />

        <Modal
          title={title}
          open={open}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <UpdateClass editClass={editClass} onCloseModal={handleCancel} ref={childRef} />
        </Modal>

        <Modal
          title="添加学生到班级"
          open={isAddStudentModalOpen}
          onOk={handleAddStudentOk}
          onCancel={handleAddStudentCancel}
          okText="确认"
          cancelText="取消"
        >
          <Form form={addStudentModelForm} layout="vertical" onFinish={onAddStudentFinish}>
            <Form.Item label="班级名称" name="className">
              <Input disabled />
            </Form.Item>

            <Form.Item
              label="选择学生"
              name="students"
              rules={[{ required: true, message: '请选择至少一个学生！' }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择学生"
                options={isAbleAddClassStudents.map((student) => ({
                  value: student.id,
                  label: student.realName,
                }))}
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </>
  );
};

export default ManageClass;
